<?php

namespace Tbqphplib\Article;

use Encore\Admin\Form\Field;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpFoundation\Response;

class Form extends \Encore\Admin\Form
{

    public function store()
    {
        $data = \request()->all();

        // Handle validation errors.
        if ($validationMessages = $this->validationMessages($data)) {
            return $this->responseValidationError($validationMessages);
        }

        if (($response = $this->prepare($data)) instanceof Response) {
            return $response;
        }

        DB::transaction(function () {
            $inserts = $this->prepareInsert($this->updates);

            foreach ($inserts as $column => $value) {
                $this->model->setAttribute($column, $value);
            }
            $this->model->setAttribute('created_by', \Encore\Admin\Facades\Admin::user()->id);
            $this->model->setAttribute('updated_by', \Encore\Admin\Facades\Admin::user()->id);
            $this->model->setAttribute('uuid', md5(uniqid() . mt_rand()));

            $this->model->save();

            //标签
            $keywords = $this->relations['keywords'];
            $keywords = explode(',', $keywords);
            $articleTagsLink = [];
            foreach ($keywords as $value) {
                $value = trim($value);
                if (empty($value)) {
                    continue;
                }
                $articleTagsLink[] = [
                    'article_id' => $this->model->id,
                    'tag_id' => $this->getTagid($value),
                ];
            }
            if ($articleTagsLink) {
                DB::table('article_tag_link')->insertOrIgnore($articleTagsLink);
            }
            // Log::debug($this->relations);
            // $this->updateRelation($this->relations);
        });

        if (($response = $this->callSaved()) instanceof Response) {
            return $response;
        }

        if ($response = $this->ajaxResponse(trans('admin.save_succeeded'))) {
            return $response;
        }

        return $this->redirectAfterStore();
    }

    private function getTagid($tagname)
    {
        $tagname = trim($tagname);
        $id = DB::table('article_tags')->where('name', $tagname)->value('id');
        $id = intval($id);
        if (!$id) {
            $id = DB::table('article_tags')->insertGetId(['name' => $tagname]);
        }
        return $id;
    }
    protected function setFieldValue($id)
    {
        $relations = $this->getRelations();

        $builder = $this->model();

        if ($this->isSoftDeletes) {
            $builder = $builder->withTrashed();
        }

        $this->model = $builder->with($relations)->findOrFail($id);

        $this->callEditing();

        $data = $this->model->toArray();

        $data['keywords'] = function () use ($data) {
            $rt = [];
            foreach ($data['keywords'] as $key => $value) {
                array_push($rt, $value['name']);
            }
            return implode(',', $rt);
        };

        $this->fields()->each(function (Field $field) use ($data) {
            if (!in_array($field->column(), $this->ignored, true)) {
                $field->fill($data);
            }
        });
    }
    public function update($id, $data = null)
    {
        $data = ($data) ?: request()->all();

        $isEditable = $this->isEditable($data);

        if (($data = $this->handleColumnUpdates($id, $data)) instanceof Response) {
            return $data;
        }

        /* @var Model $this ->model */
        $builder = $this->model();

        if ($this->isSoftDeletes) {
            $builder = $builder->withTrashed();
        }

        $this->model = $builder->with($this->getRelations())->findOrFail($id);

        $this->setFieldOriginalValue();

        // Handle validation errors.
        if ($validationMessages = $this->validationMessages($data)) {
            if (!$isEditable) {
                return back()->withInput()->withErrors($validationMessages);
            }

            return response()->json(['errors' => Arr::dot($validationMessages->getMessages())], 422);
        }

        if (($response = $this->prepare($data)) instanceof Response) {
            return $response;
        }

        DB::transaction(function () {
            $updates = $this->prepareUpdate($this->updates);

            foreach ($updates as $column => $value) {
                /* @var Model $this ->model */
                $this->model->setAttribute($column, $value);
            }

            $this->model->save();

            //标签
            $keywords = $this->relations['keywords'];
            $keywords = explode(',', $keywords);
            $articleTagsLink = [];
            foreach ($keywords as $value) {
                $value = trim($value);
                if (empty($value)) {
                    continue;
                }
                $articleTagsLink[] = [
                    'article_id' => $this->model->id,
                    'tag_id' => $this->getTagid($value),
                ];
            }
            if ($articleTagsLink) {
                DB::table('article_tag_link')->insertOrIgnore($articleTagsLink);
            }
            // Log::debug($this->relations);
            // $this->updateRelation($this->relations);
        });

        if (($result = $this->callSaved()) instanceof Response) {
            return $result;
        }

        if ($response = $this->ajaxResponse(trans('admin.update_succeeded'))) {
            return $response;
        }

        return $this->redirectAfterUpdate($id);
    }
}
